/* eslint-disable react/jsx-key */
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Switch, Modal, Button, Form, Popconfirm, message, Tooltip } from 'antd';
import { connect, useRequest } from 'umi';
import AutoTable from '@/components/AutoTable';
import InitForm from '@/components/InitForm';
import { getFetch, postFetch } from '@/utils/doFetch';
import {
  lendagree,
  handoveragree,
  givebackagree,
  lendout,
  handoveroutstore,
} from '@/services/dossier';
import CompanyName from '@/components/CompanyName';


import moment from 'moment';

let Dossier = (props) => {
  const { global, dispatch } = props;
  let actionRef = useRef(),
    ChildRef = null,
    [vs, cvs] = useState(false), //表单显/隐
    [fields, cf] = useState({}),
    [iftype, ciftype] = useState({}),
    [key, setkey] = useState('1'),
    [formRef] = Form.useForm();
  const [selectedRowKeys, setselectedRowKeys] = useState({
    1: [],
    2: [],
    3: [],
  });
  const [selectedRows, setSelectedRows] = useState({
    1: [],
    2: [],
    3: [],
  });

  const { run, loading } = useRequest(postFetch, {
    manual: true,
    formatResult: (res) => res,
    onSuccess: (result, params) => {
      message.destroy();
      if (result.code == 0) {
        message.success(result.message);
        actionRef.current.reload();
        cvs(false);
      } else {
        message.error(result.message);
      }
    },
  });

  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
    setselectedRowKeys({
      1: [],
      2: [],
      3: [],
    });
    setSelectedRows([]);
  }

  const columns = useMemo(() => {
    let extracolumns =
      key == '1'
        ? [
            {
              title: '出借人',
              dataIndex: 'lend_user_name',
              key: 'lend_user_name',
              search: false,
            },
            {
              title: '出借信息',
              dataIndex: 'lend_message',
              key: 'lend_message',
              search: false,
            },
          ]
        : key == '2'
        ? [
            {
              title: '交接人',
              dataIndex: 'hand_over_user_name',
              key: 'hand_over_user_name',
              search: false,
            },
            {
              title: '交接信息',
              dataIndex: 'hand_over_message',
              key: 'hand_over_message',
              search: false,
            },
          ]
        : [];

    return [
      {
        title: '凭证入库条码号',
        dataIndex: 'voucher_barcode',
        key: 'voucher_barcode',
      },
      {
        title: '存放位置',
        dataIndex: 'address',
        key: 'address',
        search: false,
        renderText: (text, row) => {
          return (
            <Tooltip title={text + row.rule_code} placement="topLeft">
              <span className="oneline">{text + row.rule_code}</span>
            </Tooltip>
          );
        },
      },
      {
        title: '公司名称',
        width: 260,
        dataIndex: 'company_name',
        key: 'company_name',
        render: (_, row) => (
          <CompanyName
            row={{ ...row, name: row?.company_name ?? row?.name, id: row?.company_id ?? row?.id }}
            reload={reload}
          />
        ),
      },
      {
        title: '凭证月份',
        dataIndex: 'voucher_date',
        key: 'voucher_date',
        valueType: 'dateMonth',
      },
      {
        title: '区域',
        dataIndex: 'area_name',
        key: 'area_name',
        search: false,
      },

      {
        title: '入库日期',
        dataIndex: 'submit_date',
        key: 'submit_date',
        valueType: 'date',
        render: (text, row) => {
          return (
            <span>
              {row.submit_date ? moment(row.submit_date).format('YYYY-MM-DD HH:mm:ss') : '-'}
            </span>
          );
        },
      },
      {
        title: '状态',
        dataIndex: 'process_status_name',
        key: 'process_status_name',
        search: false,
      },
      ...extracolumns,
      {
        title: '操作',
        valueType: 'option',
        width: 160,
        render: (text, row, _, action) => extraAction(text, row, _, action),
      },
    ];
  }, [key]);

  function extraAction(text, record, _, action) {
    return key == '3'
      ? [
          <Popconfirm
            title="确认入库该凭证？"
            onConfirm={() => {
              givebackagree({ ids: [record.id] }).then((res) => {
                if (res.code == 0) {
                  message.success('操作成功');
                  reload();
                }
              });
            }}
            disabled={record.process_status != 'give_back_pending'}
          >
            <a disabled={record.process_status != 'give_back_pending'}>入库</a>
          </Popconfirm>,
          <Popconfirm
            title="确认出库该凭证？"
            onConfirm={() => {
              if (record.process_status == 'hand_over_out_pending') {
                handoveroutstore({ ids: [record.id] }).then((res) => {
                  if (res.code == 0) {
                    message.success('操作成功');
                    reload();
                  }
                });
              } else {
                lendout({ ids: [record.id] }).then((res) => {
                  if (res.code == 0) {
                    message.success('操作成功');
                    reload();
                  }
                });
              }
            }}
            disabled={
              record.process_status != 'lend_out_pending' &&
              record.process_status != 'hand_over_out_pending'
            }
          >
            <a
              disabled={
                record.process_status != 'lend_out_pending' &&
                record.process_status != 'hand_over_out_pending'
              }
            >
              出库
            </a>
          </Popconfirm>,
        ]
      : [
          <>
            <a
              onClick={() => {
                // key == '2' ? '确认同意交接' : '确认同意出借'
                ciftype({
                  val: 'agree',
                  ids: [record.id],
                  title: key == '2' ? '同意交接' : '同意出借',
                });
                cf(() => {
                  if (key == '2') {
                    return {
                      handle_over_archivist_id: {
                        value: null,
                        type: 'select',
                        title: '交接档案审核人',
                        name: ['handle_over_archivist_id'],
                        required: false,
                        col: { span: 24 },
                        options: {
                          database: async () =>
                            await getFetch({
                              url: ' /wbn-api/voucher/examine_user_list',
                              params: { area_id: record.area_id },
                            }),
                          // database: user,
                          // params: { is_all: 1 },
                        },
                      },
                    };
                  } else {
                    return {
                      lend_out_archivist_id: {
                        value: null,
                        type: 'select',
                        title: '出借档案审核人',
                        name: ['lend_out_archivist_id'],
                        required: true,
                        col: { span: 24 },
                        options: {
                          database: async () =>
                            await getFetch({
                              url: ' /wbn-api/voucher/examine_user_list',
                              params: { area_id: record.area_id },
                            }),
                        },
                      },
                    };
                  }
                });
                cvs(true);
              }}
            >
              同意
            </a>
            <a
              style={{ color: 'red' }}
              onClick={() => {
                ciftype({
                  val: 'refuse',
                  ids: [record.id],
                  title: key == '2' ? '拒绝交接' : '拒绝出借',
                });
                cf(() => {
                  return {
                    message: {
                      value: null,
                      type: 'textarea',
                      title: '备注',
                      name: ['message'],
                      required: false,
                      col: { span: 24 },
                    },
                  };
                });
                cvs(true);
              }}
            >
              拒绝
            </a>
          </>,
        ];
  }

  let saveData = (values, fn) => {
    if (iftype.val == 'refuse') {
      dispatch({
        type: key == '1' ? 'dossier/lendrefuse' : 'dossier/handoverrefuse',
        payload: { ...values, ids: iftype.ids },
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    }
    if (iftype.val == 'agree') {
      if (key == '1') {
        lendagree({ ...values, ids: iftype.ids }).then((res) => {
          if (res.code == 0) {
            message.success('操作成功');
            reload();
            cvs(false);
          }
        });
      } else {
        handoveragree({ ...values, ids: iftype.ids }).then((res) => {
          if (res.code == 0) {
            message.success('操作成功');
            reload();
            cvs(false);
          }
        });
      }
    }
  };

  return (
    <div className="nopa autotable">
      <AutoTable
        tabList={[
          {
            key: '1',
            tab: '出借审核',
          },
          {
            key: '2',
            tab: '交接审核',
          },
          {
            key: '3',
            tab: '档案管理员审核',
          },
        ]}
        onTabChange={(val) => {
          setkey(val);
        }}
        pagetitle={props.route.name}
        columns={columns}
        actionRef={actionRef}
        onRef={(node) => (ChildRef = node)}
        extraparams={{ type: key, is_all: 1 }}
        path="/wbn-api/voucher/voucher_manage"
        rowSelection={{
          selectedRowKeys: selectedRowKeys[key],
          preserveSelectedRowKeys: true,
          onChange: (selectedRowKeys, selectedRows) => {
            setselectedRowKeys((s) => ({ ...s, [key]: selectedRowKeys }));
            setSelectedRows((s) => ({ ...s, [key]: selectedRows }));
          },
          // getCheckboxProps: (record) => ({
          //   disabled: key == '3' && record.status != 'pending', // Column configuration not to be checked
          // }),
        }}
        tabBarExtraContent={
          <div className="center" style={{ gap: 16 }}>
            {key == '3'
              ? [
                  <Popconfirm
                    title="确认入库该凭证？"
                    onConfirm={() => {
                      givebackagree({ ids: selectedRowKeys[key] }).then((res) => {
                        if (res.code == 0) {
                          message.success('操作成功');
                          reload();
                        }
                      });
                    }}
                  >
                    <Tooltip placement="bottom" title="请全部选择下方入库为蓝色的数据">
                      <a disabled={selectedRowKeys[key].length == 0}>入库</a>
                    </Tooltip>
                  </Popconfirm>,
                  <Popconfirm
                    title="确认出库该凭证？"
                    onConfirm={() => {
                      const out = selectedRows[key]
                        ?.filter((it) => it.process_status == 'hand_over_out_pending')
                        ?.map((it) => it.id);
                      const outs = selectedRows[key]
                        ?.filter((it) => it.process_status != 'hand_over_out_pending')
                        ?.map((it) => it.id);

                      if (out.length > 0) {
                        handoveroutstore({ ids: out }).then((res) => {
                          if (res.code == 0) {
                            message.success('操作成功');
                            reload();
                          }
                        });
                      }
                      if (outs.length > 0) {
                        lendout({ ids: outs }).then((res) => {
                          if (res.code == 0) {
                            message.success('操作成功');
                            reload();
                          }
                        });
                      }
                    }}
                  >
                    <Tooltip placement="bottom" title="请全部选择下方出库为蓝色的数据">
                      <a disabled={selectedRowKeys[key].length == 0}>出库</a>
                    </Tooltip>
                  </Popconfirm>,
                ]
              : [
                  <Popconfirm
                    title={key == '2' ? '确认同意交接' : '确认同意出借'}
                    onConfirm={() => {
                      if (key == '1') {
                        lendagree({ ids: selectedRowKeys[key] }).then((res) => {
                          if (res.code == 0) {
                            message.success('操作成功');
                            reload();
                          }
                        });
                      } else {
                        handoveragree({ ids: selectedRowKeys[key] }).then((res) => {
                          if (res.code == 0) {
                            message.success('操作成功');
                            reload();
                          }
                        });
                      }
                    }}
                  >
                    <a
                      disabled={selectedRowKeys[key].length == 0}
                      onClick={() => {
                        if (selectedRowKeys[key].length == 0) {
                          return;
                        }
                        ciftype({
                          val: 'agree',
                          ids: selectedRowKeys[key],
                          title: key == '2' ? '同意交接' : '同意出借',
                        });

                        const curarea_ids = selectedRows[key]?.map((it) => {
                          return it?.area_id;
                        });

                        const uniqueArray = [...new Set(curarea_ids)];
                        if (uniqueArray?.length > 1) {
                          message.warn('选择了不同区域的凭证,无法批量报送');
                          return;
                        }

                        cf(() => {
                          if (key == '2') {
                            return {
                              handle_over_archivist_id: {
                                value: null,
                                type: 'select',
                                title: '交接档案审核人',
                                name: ['handle_over_archivist_id'],
                                required: false,
                                col: { span: 24 },
                                options: {
                                  database: async () =>
                                    await getFetch({
                                      url: ' /wbn-api/voucher/examine_user_list',
                                      params: { area_id: uniqueArray[0] },
                                    }),
                                  // database: user,
                                  // params: { is_all: 1 },
                                },
                              },
                            };
                          } else {
                            return {
                              lend_out_archivist_id: {
                                value: null,
                                type: 'select',
                                title: '出借档案审核人',
                                name: ['lend_out_archivist_id'],
                                required: true,
                                col: { span: 24 },
                                options: {
                                  database: async () =>
                                    await getFetch({
                                      url: ' /wbn-api/voucher/examine_user_list',
                                      params: { area_id: uniqueArray[0] },
                                    }),
                                },
                              },
                            };
                          }
                        });
                        cvs(true);
                      }}
                    >
                      同意
                    </a>
                  </Popconfirm>,
                  <a
                    disabled={selectedRowKeys[key].length == 0}
                    style={{
                      color: selectedRowKeys[key].length == 0 ? 'rgba(0, 0, 0, 0.25)' : 'red',
                    }}
                    onClick={() => {
                      ciftype({
                        val: 'refuse',
                        ids: selectedRowKeys[key],
                        title: key == '2' ? '拒绝交接' : '拒绝出借',
                      });
                      cf(() => {
                        return {
                          message: {
                            value: null,
                            type: 'textarea',
                            title: '备注',
                            name: ['message'],
                            required: false,
                            col: { span: 24 },
                          },
                        };
                      });
                      cvs(true);
                    }}
                  >
                    拒绝
                  </a>,
                ]}
          </div>
        }
      />

      <Modal
        maskClosable={false}
        title={iftype.title}
        open={vs}
        onCancel={() => cvs(false)}
        footer={false}
        destroyOnClose={true}
      >
        <InitForm
          formRef={formRef}
          fields={fields}
          submitData={(values, fn) => {
            saveData(values, fn);
          }}
          onChange={(changedValues, allValues) => {}}
          submitting={loading || !vs}
          halfsave={false}
        />
      </Modal>
    </div>
  );
};

export default connect(({ global, loading }) => ({
  global,
  loading,
}))(Dossier);
